#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/ipc.h>

using namespace std;

const char *pathname = "/root";
const int proj_id = 0x66;
// 内存空间大小
const int defaultsize = 4096;

std::string To_Hex(key_t flag)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", flag);

    return buffer;
}

key_t GetShmKeyOrDie() // 创建共享内存唯一key值
{
    key_t k = ftok(pathname, proj_id); // 通过用户传的唯一路径名字参数 内部算法演算出k值使其重复率降低
    if (k < 0)
    {
        cerr << "ftok error:" << errno << " " << strerror(errno) << endl;
        exit(1);
    }

    return k;
}

int CreateShmOrDie(key_t key, int size, int flag) // 创建共享内存并获取共享内存id
    // flag
    // IPC_CREAT: 不存在就创建，存在就获取
    // IPC_EXCL: 没有意义
    // IPC_CREAT | IPC_EXCL: 不存在就创建，存在就出错返回
{
    umask(0);
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        cerr << "get shmid error" << errno << " " << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(key_t key, int size)
{
    // IPC_CREAT: 不存在就创建，存在就获取
    // IPC_EXCL: 没有意义
    // IPC_CREAT | IPC_EXCL: 不存在就创建，存在就出错返回
    return CreateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT);
}

void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n < 0)
    {
        cerr << "Delete error:" << errno << strerror(errno) << endl;
    }
    else
    {
        cout << "delete success" << endl;
    }
}

void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid, IPC_STAT, &shmds);
    if (n < 0)
    {
        std::cerr << "shmctl error" << std::endl;
        return;
    }
    std::cout << "shmds.shm_segsz: " << shmds.shm_segsz << std::endl;
    std::cout << "shmds.shm_nattch:" << shmds.shm_nattch << std::endl;
    std::cout << "shmds.shm_ctime:" << shmds.shm_ctime << std::endl;
    std::cout << "shmds.shm_perm.__key:" << To_Hex(shmds.shm_perm.__key) << std::endl;
}

void *Shmattach(int shmid)
{
    void *addr = shmat(shmid, nullptr, 0);
    if ((long long int)addr == -1)
    {
        cerr << "shmat error:" << errno << strerror(errno) << endl;
        return nullptr;
    }
    return addr;
}
void Shmdelete(void *shmaddr)
{
    int n = shmdt(shmaddr);
    if (n < 0)
    {
        cerr << "shmdterror:" << errno << strerror(errno) << endl;
        exit(3);
    }
}